﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace furion.blog.Domain.Query
{
    /// <summary>
    /// 基础分页查询实体
    /// </summary>
    public abstract class BasePageQuery
    {

        public int Page { get; set; } = 1;
        public int Limit { get; set; } = 20;
        public long PageCount { get; set; } = 1;
        public long RecordCount { get; set; } = 0;
        public long GetStartIndex()
        {
            return (this.Page - 1) * Limit;
        }

        /// <summary>
        /// 查询的列
        /// </summary>
        public abstract string Columns();

        /// <summary>
        /// 查询的表
        /// </summary>
        /// <returns></returns>
        public abstract string Tables();

        /// <summary>
        /// 获取总数量sql
        /// </summary>
        /// <returns></returns>
        public string GetCountSQL()
        {
            var (strWhere, sqlParams) = QueryParams();
            return " select count(*) from (select " + Columns() + " from " + Tables() + " where 1=1 " + strWhere + " ) t ";
        }

        /// <summary>
        /// 获取数据sql
        /// </summary>
        /// <returns></returns>
        public string GetDataSQL()
        {
            var (strWhere, sqlParams) = QueryParams();
            return " select " + Columns() + " from " + Tables() +
                " where t.ts<=(select t.ts from " + Tables() + " where 1=1 " + strWhere + " order by t.ts desc limit " + GetStartIndex() + ",1 ) " +
                " " + strWhere + " order by t.ts desc limit " + Limit;
        }

        
        

        /// <summary>
        /// 返回查询where 和 条件参数
        /// </summary>
        /// <returns></returns>
        public abstract (string, List<SugarParameter>) QueryParams();
       

    }
}
